use std::{cell::RefCell, rc::Rc, string};

use deno_core::{op2, v8, OpState};
use QcCore::{ecs::component::Named, scene_system::scene::Scene};
use QcUI::component::{Button, Canvas, ToUi};

use crate::utils::GoExt;

#[op2]
pub fn opSetButtonText<'a>(
    state: &mut OpState,
    scope: &mut v8::HandleScope<'a>,
    this: v8::Local<v8::Object>,
    #[string] name: &str,
) -> v8::Local<'a, v8::Value> {
    let scene = state.borrow_mut::<*mut Scene>();
    let scene = unsafe { &mut **scene };

    if let Some(index) = scene.get_main_canvas() {
        if let Some(canvas) = scene[index].getComponentMut::<Canvas>() {
            if let Some(index) = GoExt::get_uuid(scope, this) {
                if let Some(node) = canvas.get_mut(index) {
                    let node = node.asAnyMut().downcast_mut::<Button>().unwrap();
                    node.set_text(name);
                }
            }
        }
    }

    v8::undefined(scope).into()
}

#[op2]
pub fn opGetButtonText<'a>(
    state: &mut OpState,
    scope: &mut v8::HandleScope<'a>,
    this: v8::Local<v8::Object>,
) -> v8::Local<'a, v8::Value> {
    let scene = state.borrow_mut::<*mut Scene>();
    let scene = unsafe { &mut **scene };

    if let Some(index) = scene.get_main_canvas() {
        if let Some(canvas) = scene[index].getComponent::<Canvas>() {
            if let Some(index) = GoExt::get_uuid(scope, this) {
                if let Some(node) = canvas.get(index) {
                    let node = node.asAny().downcast_ref::<Button>().unwrap();

                    return v8::String::new(scope, &node.text).unwrap().into();
                }
            }
        }
    }

    v8::undefined(scope).into()
}

#[op2]
pub fn opCreateButton<'a>(
    state: &mut OpState,
    scope: &mut v8::HandleScope<'a>,
) -> v8::Local<'a, v8::Value> {
    let scene = state.borrow_mut::<*mut Scene>();
    let scene = unsafe { &mut **scene };

    if let Some(index) = scene.get_main_canvas() {
        if let Some(canvas) = scene[index].getComponentMut::<Canvas>() {
            let button = Button::default().toUi();
            let uuid = canvas.insert(button);

            let node = v8::Object::new(scope);
            GoExt::set_uuid(scope, node, uuid);
            GoExt::set_prototype(scope, node, Button::typeName());

            return node.into();
        }
    }

    v8::undefined(scope).into()
}
